package org.example.examfx02.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.example.examfx02.entity.*;
import org.example.examfx02.HelloApplication;
import org.example.examfx02.tool.StringUtil;
import org.example.examfx02.tool.SystemData;
import org.example.examfx02.tool.WriteFile;

import java.util.List;

public class MainViewController {
    public static SystemData sys = SystemData.getInstance();
    @FXML
    TextField textline;
    @FXML
    Button addTeacher;
    @FXML
    Button addStudent;
    @FXML
    Button delTeacher;
    @FXML
    Button delStudent;
    @FXML
    Button resetStudent;
    @FXML
    Button resetTeacher;
    @FXML
    Button changedBtn;
    @FXML
    Button addBtn;
    @FXML
    Button deleteBtn;
    @FXML
    Button findBtn;
    @FXML
    Button updateBtn;
    @FXML
    Button sortBtn;
    @FXML
    Button saveStudentBtn;
    @FXML
    Button saveTeacherBtn;
    @FXML
    Button saveCourseBtn;
    @FXML
    TableView<Course> courseTable;
    @FXML
    TableColumn<Course,String> courseID;
    @FXML
    TableColumn<Course,String> courseName;
    @FXML
    TableColumn<Course,String> courseTeacher;
    @FXML
    TableColumn<Course,Integer> courseNum;
    @FXML
    TableColumn<Course,String> courseType;
    @FXML
    TableColumn<Course,Integer> courseCredit;
    @FXML
    TableColumn<Course,Integer> courseMaxNum;
    // TABLE 2
    @FXML
    TableView<Student> studentTable;
    @FXML
    TableColumn<Student,String> stuID;
    @FXML
    TableColumn<Student,String> stuName;
    @FXML
    TableColumn<Student,String> stuClass;
    @FXML
    TableColumn<User,String> stuPassword;
    // TABLE 3
    @FXML
    TableView<Teacher> teacherTable;
    @FXML
    TableColumn<Teacher,String> teacherID;
    @FXML
    TableColumn<Teacher,String> teacherName;
    @FXML
    TableColumn<Teacher,String> teacherLevel;
    @FXML
    TableColumn<User,String> teaPassword;
    @FXML
    ChoiceBox<String> chooseType;
    ObservableList<String> chooseList;

    // 创建通用的居中对齐单元格工厂方法
    public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> createCenteredCellFactory() {
        return column -> new TableCell<S, T>() {
            @Override
            protected void updateItem(T item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(item.toString());
                }
                // 设置单元格内容居中
                setAlignment(Pos.CENTER);
            }
        };
    }
    public void initCourse(){
//        sys.setCourses(ReadFile.readCourseFile());
        List<Course> courses = sys.getCourses();
        courseID.setCellValueFactory(new PropertyValueFactory<>("id"));
        courseName.setCellValueFactory(new PropertyValueFactory<>("name"));
        courseNum.setCellValueFactory(new PropertyValueFactory<>("chooseNum"));
        courseTeacher.setCellFactory(column ->new TeacherNameCell());
        courseType.setCellFactory(column -> new TypeCell());
        courseCredit.setCellFactory(column->new CreditCell());
        courseMaxNum.setCellFactory(column -> new MaxNumCell());
        // 为公共列设置居中显示
        courseID.setCellFactory(createCenteredCellFactory());
        courseName.setCellFactory(createCenteredCellFactory());
        courseNum.setCellFactory(createCenteredCellFactory());
        courseTable.setItems(FXCollections.observableArrayList(courses));
    }
    public void initStudent(){
//        sys.getUserGroup().setStudents(ReadFile.readStuFile());
        List<Student> students = sys.getUserGroup().getStudents();
        stuName.setCellValueFactory(new PropertyValueFactory<>("username"));
        stuClass.setCellValueFactory(new PropertyValueFactory<>("myClass"));
        stuID.setCellValueFactory(new PropertyValueFactory<>("id"));
        stuPassword.setCellFactory(column->new UserChangedCell());
        // 设置单元格工厂，使内容居中
        stuID.setCellFactory(createCenteredCellFactory());
        stuName.setCellFactory(createCenteredCellFactory());
        stuClass.setCellFactory(createCenteredCellFactory());
        studentTable.setItems(FXCollections.observableArrayList(students));
    }
    public void initTeacher(){
//        sys.getUserGroup().setTeachers(ReadFile.readTeaFile());
        List<Teacher> teachers = sys.getUserGroup().getTeachers();
        teacherID.setCellValueFactory(new PropertyValueFactory<>("workId"));
        teacherName.setCellValueFactory(new PropertyValueFactory<>("username"));
        teacherLevel.setCellValueFactory(new PropertyValueFactory<>("level"));
        teaPassword.setCellFactory(column ->new UserChangedCell());
        // 设置单元格工厂，使内容居中
        teacherID.setCellFactory(createCenteredCellFactory());
        teacherName.setCellFactory(createCenteredCellFactory());
        teacherLevel.setCellFactory(createCenteredCellFactory());

        teacherTable.setItems(FXCollections.observableArrayList(teachers));
    }
    public void initialize(){
        chooseList = FXCollections.observableArrayList();
        chooseList.add("教师名称");
        chooseList.add("课程ID");
        chooseList.add("选课人数");
        chooseType.setItems(chooseList);
        initTeacher();
        initStudent();
        initCourse();
    }
    public void update(){
        List<Teacher> teachers = sys.getUserGroup().getTeachers();
        teacherTable.setItems(FXCollections.observableArrayList(teachers));
        List<Student> students = sys.getUserGroup().getStudents();
        studentTable.setItems(FXCollections.observableArrayList(students));
        List<Course> courses = sys.getCourses();
        courseTable.setItems(FXCollections.observableArrayList(courses));
    }
    public void add(){
        //    new AddView().start(new Stage());
        Stage addStage = HelloApplication.addView("add-view.fxml",500,260,"添加课程");
        // 为窗口添加关闭事件监听器
        addStage.setOnHidden(event -> {
            // 窗口关闭后执行刷新操作
            update();
        });
    }
    public void delete(){
        List<Course> courses = sys.getCourses();
        Course course = courseTable.getSelectionModel().getSelectedItem();
        if(course!=null){
            Alert alert = HelloApplication.showConfirmAlert("删除","确认要删除吗？");
            if(alert.getResult() == ButtonType.OK){
                courses.remove(course);
            }
        }else{
            HelloApplication.showAlert("删除","请先选择课程！！！");
        }
        update();
    }
    public void find(){
        List<Course> courses;
        if(StringUtil.isEmpty(textline.getText())){
            HelloApplication.showAlert("警告","请输入内容再进行查找");
        }else{
            String str = textline.getText();
            if(chooseType.getValue()==null){
                HelloApplication.showAlert("警告","请在下拉框中选择属性");
            }else if("教师名称".equals(chooseType.getValue())){
                courses = sys.FindCoursebyTeacher(str);
                courseTable.setItems(FXCollections.observableArrayList(courses));
            }else if("课程ID".equals(chooseType.getValue())){
                courses = sys.FindCoursebyID(str);
                courseTable.setItems(FXCollections.observableArrayList(courses));
            }else if("选课人数".equals(chooseType.getValue())){
                try{
                    courses = sys.FindCoursebynum(Integer.valueOf(str));
                    courseTable.setItems(FXCollections.observableArrayList(courses));
                }catch(Exception e){
                    HelloApplication.showAlert("警告","请检查输入是否为数字");
                }
            }
        }

    }
    public void sort(){
        ObservableList<Course> courses = courseTable.getItems();
        if(chooseType.getValue()==null){
            HelloApplication.showAlert("警告","请在下拉框中选择属性");
        }else if("教师名称".equals(chooseType.getValue())){
            SystemData.sortByTeacherName(courses);
        }else if("课程ID".equals(chooseType.getValue())){
            SystemData.sortByID(courses);
        }else if("选课人数".equals(chooseType.getValue())){
            SystemData.sortByNum(courses);
        }
    }
    public void change(){
        Stage addStage = HelloApplication.addView("change-view.fxml",500,260,"修改课程");
        addStage.setOnHidden(event -> {
            // 窗口关闭后执行刷新操作
            update();
        });
    }
    public void delStu(){
        List<Student> students = sys.getUserGroup().getStudents();
        Student student = studentTable.getSelectionModel().getSelectedItem();
        if(student!=null){
            Alert alert = HelloApplication.showConfirmAlert("删除","确认要删除吗？");
            if(alert.getResult() == ButtonType.OK){
                students.remove(student);
            }
        }else{
            HelloApplication.showAlert("删除","请先选择学生！！！");
        }
        update();
    }
    public void delTea(){
        List<Teacher> teachers = sys.getUserGroup().getTeachers();
        Teacher teacher = teacherTable.getSelectionModel().getSelectedItem();
        if(teacher!=null){
            Alert alert = HelloApplication.showConfirmAlert("删除","确认要删除吗？");
            if(alert.getResult() == ButtonType.OK){
                teachers.remove(teacher);
            }
        }else{
            HelloApplication.showAlert("删除","请先选择老师！！！");
        }
        update();
    }
    public void addTea(){
        Stage addStage = HelloApplication.addView("addTea-view.fxml",400,380,"添加用户");
        addStage.setOnHidden(event -> {
            // 窗口关闭后执行刷新操作
            update();
        });
    }
    public void addStu(){
        Stage addStage = HelloApplication.addView("addStu-view.fxml",500,350,"添加用户");
        addStage.setOnHidden(event -> {
            // 窗口关闭后执行刷新操作
            update();
        });
    }
    public void resetStu(){
        Student student = studentTable.getSelectionModel().getSelectedItem();
        if(student!=null){
            Alert alert = HelloApplication.showConfirmAlert("重置","确认要重置吗？");
            if(alert.getResult() == ButtonType.OK){
                student.setChanged(false);
                student.setPassword("123456");
            }
            sys.getUserGroup().updateStu(student);
        }else{
            HelloApplication.showAlert("删除","请先选择学生！！！");
        }
        studentTable.refresh();
    }
    public void resetTea(){
        Teacher teacher = teacherTable.getSelectionModel().getSelectedItem();
        if(teacher!=null){
            Alert alert = HelloApplication.showConfirmAlert("重置","确认要重置吗？");
            if(alert.getResult() == ButtonType.OK){
                teacher.setChanged(false);
                teacher.setPassword("123456");
            }
            sys.getUserGroup().updateTea(teacher);
        }else{
            HelloApplication.showAlert("删除","请先选择老师！！！");
        }
        teacherTable.refresh();
    }
    public void saveCourse(){
        WriteFile.writeCourseFile(sys.getCourses());
    }
    public void saveTeacher(){
        WriteFile.writeTeaFile(sys.getUserGroup().getTeachers());
    }
    public void saveStudent(){
        WriteFile.writeStuFile(sys.getUserGroup().getStudents());
    }

}
